package alternate;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wcj
 * @Date 2021/7/22 12:45
 * @Version 1.0
 */
public class ConditionImpl {

    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();
    private static volatile int count = 1;

    public static void main(String[] args) {

        // 奇数线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    // 首先，要获取锁资源
                    lock.lock();
                    try {
                        if (count > 100) {
                            break;
                        }
                        if (count % 2 == 1) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                        }
                        condition.signal();
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        }, "奇数线程").start();

        // 偶数线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    lock.lock();
                    try {
                        if (count > 100) {
                            break;
                        }
                        if (count % 2 == 0) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                        }
                        condition.signal();
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        }, "偶数线程").start();
    }
}
